import * as ReactDOM from 'react-dom';
import {Table} from 'antd';
import classNames from 'classnames';
import RcTable from 'rc-table';
import React from 'react';
import {ColumnProps, TableLocale, TableProps} from "antd/lib/table";
import {SpinProps} from "antd/lib/spin";



export interface ExpandColumnProps<T> extends ColumnProps<T>{
  expandIndex:number; //扩展后 index的排序位置
  expandWidth:number; //扩展后 预计占用的宽度 ，不是实际宽度（实际宽度用width）
}

export interface ExpandColumn<T> {
  expandIndex:number; //扩展后 index的排序位置
  expandWidth:number; //扩展后 预计占用的宽度 ，不是实际宽度（实际宽度用width）
  expandRangeWidth:number;// expandIndex = 0 到 当前expandIndex 的width 总和
  originIndex:number; //原始值 column 的 index
  column:ColumnProps<T>;

}


export default class ExpandTable<T> extends Table<T>{

  tableWidth:number = 0;
  tableHeight:number = 0;

  expandColumns:ExpandColumn<T>[];//扩展后colums集合
  expandColumnsSumWidth:number;//扩展后 所有宽度预计总和，配置由expandWidth累计计算

  constructor(props: TableProps<T>){

    super(props);

    /*获取当前window 下 table的 宽和高*/
    this.expandColumns = [];
    this.tableWidth = document.documentElement.clientWidth || document.body.clientWidth;
    this.tableHeight = document.documentElement.clientHeight || document.body.clientHeight;
    console.log('初始化 table Width ' + this.tableWidth);
    console.log('初始化 table Height ' + this.tableHeight);

    Object.keys(this.columns).forEach((columnKey) => {

      let tempColumn:ColumnProps<T> = this.columns[columnKey];
      this.expandColumns.push({
        originIndex:columnKey,
        expandWidth:tempColumn.expandWidth,
        expandIndex:tempColumn.expandIndex,
        expandRangeWidth:0,
        column:tempColumn
      });

    });

    console.log('this.expandColumns ');
    console.log(this.expandColumns);

    this.expandColumns.sort(this.comparaExpandColomn)


    let rangeWidth:number = 50;//折叠按钮宽度
    Object.keys(this.expandColumns).forEach((columnKey) => {
      let tempColumn:ExpandColumn<T> = this.expandColumns[columnKey];
      tempColumn.expandRangeWidth = rangeWidth + tempColumn.expandWidth ;
      rangeWidth = tempColumn.expandRangeWidth;
    })
    this.expandColumnsSumWidth = rangeWidth;

    console.log('this.expandColumns 排序 ');

    console.log(this.expandColumns);
    console.log(this.expandColumnsSumWidth);

  }


  componentDidMount() {
    this.updateSize();
    window.addEventListener('resize', this.updateSize.bind(this));
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateSize.bind(this));
  }

  updateSize() {
    try {
      const parentDom = ReactDOM.findDOMNode(this).parentNode;
      let {width, height} = this.props;
      if (!width) {
        width = parentDom.offsetWidth;
      }
      if (!height) {
        height = parentDom.offsetHeight - parentDom.offsetTop;
      }
      if(this.tableWidth != width ){
        console.log('tablewidth ' + this.tableWidth);
        console.log('width ' + width);
        //当前和之前的宽度都大于 响应式列表最低宽度要求  不做更新处理。
        if (this.tableWidth > this.expandColumnsSumWidth && width > this.expandColumnsSumWidth){

        }
        else {
          this.tableWidth = width;
          this.tableHeight = height;
          console.log('this.forceUpdate()');
          this.forceUpdate();
        }

      }
      this.tableWidth = width;
      this.tableHeight = height;

    } catch (ignore) {
    }
  }
  renderTable = (contextLocale: TableLocale, loading: SpinProps) => {
    console.log('HYExpandTable  renderTable')

    const locale = { ...contextLocale, ...this.props.locale };
    const { style, className, prefixCls, showHeader, ...restProps } = this.props;
    const data = this.getCurrentPageData();
    let expandIconAsCell = this.props.expandedRowRender && this.props.expandIconAsCell !== false;

    const classString = classNames({
      [`${prefixCls}-${this.props.size}`]: true,
      [`${prefixCls}-bordered`]: this.props.bordered,
      [`${prefixCls}-empty`]: !data.length,
      [`${prefixCls}-without-column-header`]: !showHeader,
    });

    let columns = this.renderRowSelection(locale);

    let expandColumns = [];
    let hideColumns = [];
    let expandedRowRender;
    if (this.tableWidth <= this.expandColumnsSumWidth){//小于预计总和，就得显示 【展开按钮】
      let tempExpandColumns = [];
      for(let index:number = 0; index < this.expandColumns.length ; index++) {
        let tempColumn:ExpandColumn<T> =  this.expandColumns[index];
        if (tempColumn.expandRangeWidth < this.tableWidth || index === 0){
          tempExpandColumns.push(tempColumn);
        }
        else {
          hideColumns.push(tempColumn);
        }
      }

      tempExpandColumns.sort(this.comparaColomn);
      expandColumns = tempExpandColumns.map((tempColumn) => {
        return tempColumn.column;
      })

      if(this.comparaExpandColomn.length !== columns.length &&
        columns[0].key === 'selection-column'){
        expandColumns.splice(0,0,columns[0]);
      }

    }
    else {
      expandColumns = columns;
    }

    if(hideColumns && hideColumns.length > 0){
      hideColumns.sort(this.comparaColomn);
      expandIconAsCell = true;
      /*展开项 显示处理*/
      // (text: any, record: T, index: number)
      expandedRowRender = rowData => {
        return <ul className="expanded-list">
          {
            hideColumns.map((tempColumn, i) => {
              return <li className="expanded-row" key={i} >
                {tempColumn.column.title}:
                {rowData[tempColumn.column.key]? rowData[tempColumn.column.key] :
                  this.renderColumnTitle(tempColumn.column.render(rowData[tempColumn.column.key],rowData,i))}</li>;
            })
          }
        </ul>
      }
    }
    else {
      expandIconAsCell = false;
    }

    //添加过滤器等功能
    columns = this.renderColumnsDropdown(expandColumns, locale);
    columns = columns.map((column, i) => {
      const newColumn = { ...column };
      newColumn.key = this.getColumnKey(newColumn, i);
      return newColumn;
    });
    let expandIconColumnIndex = (columns[0] && columns[0].key === 'selection-column') ? 1 : 0;
    if ('expandIconColumnIndex' in restProps) {
      expandIconColumnIndex = restProps.expandIconColumnIndex as number;
    }

    return (
      <RcTable
        key="table"
        {...restProps}
        expandedRowRender={expandedRowRender}
        onRow={this.onRow}
        components={this.components}
        prefixCls={prefixCls}
        data={data}
        columns={columns}
        showHeader={showHeader}
        className={classString}
        expandIconColumnIndex={expandIconColumnIndex}
        expandIconAsCell={expandIconAsCell}
        emptyText={!loading.spinning && locale.emptyText}
      />
    );
  }

  comparaExpandColomn (obj1, obj2):number {
    var val1 = obj1.expandIndex;
    var val2 = obj2.expandIndex;
    if (val1 < val2) {
      return -1;
    } else if (val1 > val2) {
      return 1;
    } else {
      return 0;
    }
  }
  comparaColomn (obj1, obj2):number {
    var val1 = obj1.originIndex;
    var val2 = obj2.originIndex;
    if (val1 < val2) {
      return -1;
    } else if (val1 > val2) {
      return 1;
    } else {
      return 0;
    }
  }



}
